
import _ from 'lodash'
import protoAPI from '../../config/proto-api'
import * as protoProxy from '../../proxys/proto'
import { CustomError } from '../../error'

export const asyncSend = (data, req, res, next) => {
  let { rtsp_key } = req.headers
  let { name, opts, auth } = data
  let setting = _.find(protoAPI, o => o.name === name) || {}
  let { callback } = setting
  return protoProxy.asyncSend(name, opts, rtsp_key)
    .then( ret => {
      if (callback) {
        return protoProxy.asyncSend(callback)
      }
      return ret
    })
    .then( ret => res.api(ret) )
    .catch(CustomError, err =>  res.api(null, err.code) )
    .catch( err => next(err) )
}